﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;

namespace CoolCode.Web.Upload
{
    public sealed class FileUpload
    {
        private HttpContextBase context = null;

        public string Type { get; set; }
        /// <summary>
        /// 保存上传文件的根目录
        /// </summary>
        public string UploadPath { get; set; }
        public int MaxLength { get; set; }


        public string PostName { get; private set; }
        public int FileLength { get; private set; }
        public string ExtName { get; private set; }
        /// <summary>
        /// 保存文件夹（默认是由系统年月组成）
        /// </summary>
        public string SavePath { get;  set; }
        /// <summary>
        /// 保存文件名（不带后缀，默认由系统时间组成）
        /// </summary>
        public string SaveName { get;  set; }

        public FileUpload(HttpContextBase httpContext)
            : this()
        {
            context = httpContext;
        }

        public FileUpload()
        {
            Type = "txt|rar|zip|jpg|jpeg|png|gif|bmp";
            PostName = string.Empty;
            SaveName = string.Empty;
            FileLength = 0;
            UploadPath = string.Empty;
            MaxLength = 1024;
            ExtName = string.Empty;
            if (context == null)
                context = new HttpContextWrapper(HttpContext.Current);
        }

        private string CreateForderName()
        {
            return DateTime.Now.ToString("yyyyMM");
        }

        private string CreateFileName()
        {
            return DateTime.Now.ToString("yyyyMMssHHmmss");
        }

        ///// <summary>
        ///// 保存上传的文件，返回保存的虚拟路径
        ///// </summary>
        ///// <returns></returns>
        //public string  Save()
        //{
        //   // HttpPostedFileBase upfile = context.Request.Files[0];
        //   // PostFile file = new PostFile(upfile);
        //   //return   Save(file);
        //   return   SaveAsThumbnail(100);
        //}

        //public string SaveAsThumbnail(int height)
        //{
        //    HttpPostedFileBase upfile = context.Request.Files[0];
        //    PostFile file = new PostFile(upfile);
        //    string vistualSavepath =GetSavePath(file);
        //    string actualSavepath = Utility.GetMapPath(vistualSavepath);
        //    ImageManager.SaveAsThumbnail(file.Buffer, height, actualSavepath);
        //    return vistualSavepath;
        //}

        public string  Save(PostFile postFile)
        {
            if (string.IsNullOrEmpty(Type))
                throw new ArgumentNullException("Type");
            if (string.IsNullOrEmpty(UploadPath))
                throw new ArgumentNullException("UploadPath");
            if (MaxLength < 0)
                throw new ArgumentOutOfRangeException("ManLength");
            PostName = postFile.Name.Substring(postFile.Name.LastIndexOf('\\') + 1);
            
            string extName = PostName.Substring(PostName.LastIndexOf('.') + 1);
            if (string.IsNullOrEmpty(extName))
                throw new Exception("无扩展名信息,该文件不被支持.");
            else
            {
                extName = extName.ToLower();
                string[] fs = Type.Split('|');
                if (!fs.Any(f => f == extName))
                    throw new Exception(string.Format("扩展名{0}不被系统支持,请重新上传.", extName));
                ExtName = extName;
            }
            FileLength = postFile.Buffer.Length;
            if (FileLength > MaxLength * 1024)
                throw new Exception(string.Format("上传文件为{0}字节,系统限制为{1},请重写上传.", FileLength, MaxLength * 1024));
            string rootPath = context.Server.MapPath(UploadPath);
            if (!Directory.Exists(rootPath))
                throw new Exception("系统错误:不存在该上传路径:" + UploadPath);
            if (string.IsNullOrEmpty(SavePath))
                SavePath = CreateForderName();
            string savePath = rootPath + '\\' + SavePath;
            if (!Directory.Exists(savePath))
                Directory.CreateDirectory(savePath);
            if (string.IsNullOrEmpty(SaveName))
                SaveName = CreateFileName();
            postFile.SaveAs(savePath + "\\" + SaveName + "." + extName);
            return    UploadPath  + "/" + SavePath + "/" + SaveName + "." + extName;
        }

        private string GetSavePath(PostFile postFile)
        {
            PostName = postFile.Name.Substring(postFile.Name.LastIndexOf('\\') + 1);
            string extName = PostName.Substring(PostName.LastIndexOf('.') + 1);
            string rootPath = context.Server.MapPath(UploadPath);
            if (!Directory.Exists(rootPath))
                throw new Exception("系统错误:不存在该上传路径:" + UploadPath);
            if (string.IsNullOrEmpty(SavePath))
                SavePath = CreateForderName();
            string savePath = rootPath + '\\' + SavePath;
            if (!Directory.Exists(savePath))
                Directory.CreateDirectory(savePath);
            if (string.IsNullOrEmpty(SaveName))
                SaveName = CreateFileName();
            return UploadPath + "/" + SavePath + "/" + SaveName + "." + extName;
        }
    }
}
